package com.zqq.demo.camera;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMuxer;


import com.zqq.base.utils.LogUtils;

import java.io.IOException;
import java.nio.ByteBuffer;

public class MediaMuxerHelper {
    private MediaMuxer muxer;
    private int videoTrackIndex = -1;
    private int audioTrackIndex = -1;
    private boolean isStarted = false;
    
    public MediaMuxerHelper(String outputPath) throws IOException {
        muxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
    }
    
    public void addVideoTrack(MediaFormat format) {
        videoTrackIndex = muxer.addTrack(format);
        startIfReady();
    }
    
    public void addAudioTrack(MediaFormat format) {
        audioTrackIndex = muxer.addTrack(format);
        startIfReady();
    }
    
    private void startIfReady() {
        if (!isStarted && videoTrackIndex != -1 && audioTrackIndex != -1) {
            muxer.start();
            isStarted = true;
        }
    }

    public void writeVideoData(ByteBuffer buffer, MediaCodec.BufferInfo info) {
        LogUtils.i("bl_h264_saver","video 》》"+info.size+"  >>"+info.presentationTimeUs);
        if (isStarted) {
            muxer.writeSampleData(videoTrackIndex, buffer, info);
        }
    }


    public void writeAudioData(ByteBuffer buffer, MediaCodec.BufferInfo info) {
        LogUtils.i("bl_h264_saver","audio 》》"+info.size+"  >>"+info.presentationTimeUs);
        if (isStarted && muxer != null) {
            muxer.writeSampleData(audioTrackIndex, buffer, info);
        }
    }
    
    public void release() {
        LogUtils.i("bl_muxer","release>>");
        if (muxer != null) {
            try {
                if (isStarted) {
                    LogUtils.i("bl_muxer","stop>>");
                    muxer.stop();
                }
                muxer.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            muxer = null;
        }
    }
}
